package com.captain.special.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/3/31 8:51
 */
public class 链表中的下一个更大节点1019 {
    public static void main(String[] args) {
        new 链表中的下一个更大节点1019().nextLargerNodes(ListNode.getInstance());
    }

    public int[] nextLargerNodes(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new int[]{0};

        List<Integer> tpList = new ArrayList<>();
        while (head != null) {
            tpList.add(head.val);
            head = head.next;
        }
        int[] flipArray = new int[tpList.size()];
        Stack<Integer> stack = new Stack<>();
        for (int i = tpList.size() - 1; i >= 0; i--) {
            Integer value = tpList.get(i);
            while (true) {
                //获取栈顶元素,没有移除
                if (stack.isEmpty()) {
                    stack.push(value);
                    flipArray[i] = 0;
                    break;
                }
                Integer peek = stack.peek();
                if (value < peek) {
                    stack.add(value);
                    flipArray[i] = peek;
                    break;
                }
                //弹出元素
                stack.pop();
            }
        }
        return flipArray;
    }
}
